<template>
  <div v-loading="infoLoading">
    <el-dialog
      :title="dialogTitle2"
      :visible.sync="dialogVisible2"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="postForm2" :model="postForm2" class="form-container" label-width="200px" :rules="rules2">
        <el-form-item label="涉及地区" prop="sjdq">
          <el-input v-model="postForm2.sjdq" style="width:200px" />
        </el-form-item>
        <el-form-item label="登记金额（万元）" prop="djje">
          <el-input-number v-model="postForm2.djje" style="width:200px" />
        </el-form-item>
        <el-form-item label="合同数" prop="hts">
          <el-input-number v-model="postForm2.hts" style="width:200px" />
        </el-form-item>
        <el-form-item label="核查登记人数" prop="hcdjrs">
          <el-input-number v-model="postForm2.hcdjrs" style="width:200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm2">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div v-if="showDuban">
      <supervise v-if="showSupervise()" business-table="bus_hcdj" :cfajbh="cfajbh" :timestamp="timestamp" />
    </div>
    <h2>核查登记</h2>
    <el-alert
      v-if="postForm.shzt===3"
      title="审核未通过"
      type="error"
      :description="'原因：'+hist.auditResult?hist.auditResult:'读取中...'"
      show-icon
    />
    <div v-if="readOnly&&!postForm.id" style="color:red;font-weight:bolder;margin-left:20px;">未录入</div>
    <el-form v-else ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="200px" :inline="true">
      <table cellspacing="0" cellpadding="0" border="0" class="formTable" style="margin-bottom:10px;">
        <tr>
          <th>登记开始时间</th>
          <td>
            <el-form-item label="" prop="djkssj">
              <el-date-picker v-if="!readOnly" v-model="postForm.djkssj" style="width:200px" value-format="yyyy-MM-dd" />
              <span v-else>{{ postForm.djkssj }}</span>
            </el-form-item>
            <!-- <el-form-item label="计划结束时间" prop="jhjssj">
        <el-date-picker v-if="!readOnly" v-model="postForm.jhjssj" style="width:200px" value-format="yyyy-MM-dd" />
        <span v-else>{{ postForm.jhjssj }}</span>
      </el-form-item> -->
          </td>
          <th>后台审计公司</th>
          <td>
            <el-form-item label="" prop="htsjgs">
              <el-input v-if="!readOnly" v-model="postForm.htsjgs" style="width:400px" />
              <span v-else>{{ postForm.htsjgs }}</span>
            </el-form-item>
          </td>
        </tr>
      </table>
      <!-- <div />
      <el-form-item label="初期侦查涉及金额（万元）" prop="cqzcsjje" style="width:500px;">
        <el-input-number v-if="!readOnly" v-model="postForm.cqzcsjje" style="width:200px" />
        <span v-else>{{ postForm.cqzcsjje }}</span>
      </el-form-item>
      <el-form-item label="初期侦查未兑付金额（万元）" prop="cqzcwdfje">
        <el-input-number v-if="!readOnly" v-model="postForm.cqzcwdfje" style="width:200px" />
        <span v-else>{{ postForm.cqzcwdfje }}</span>
      </el-form-item> -->
      <!-- <div />
      <el-form-item label="初期侦查人员" prop="cqzcry" style="width:500px;">
        <el-input v-if="!readOnly" v-model="postForm.cqzcry" style="width:200px" />
        <span v-else>{{ postForm.cqzcry }}</span>
      </el-form-item> -->
      <!-- <el-form-item label="报案人员" prop="bary">
        <el-input v-if="!readOnly" v-model="postForm.bary" style="width:200px" />
        <span v-else>{{ postForm.bary }}</span>
      </el-form-item> -->
      <!-- <div />
      <el-form-item label="核查登记金额（万元）" prop="hcdjje" style="width:500px;">
        <el-input-number v-if="!readOnly" v-model="postForm.hcdjje" disabled style="width:200px" />
        <span v-else>{{ postForm.hcdjje }}</span>
      </el-form-item>
      <el-form-item label="核查登记合同数" prop="hcdjhts">
        <el-input-number v-if="!readOnly" v-model="postForm.hcdjhts" disabled style="width:200px" />
        <span v-else>{{ postForm.hcdjhts }}</span>
      </el-form-item> -->
      <div />
      <el-button
        v-if="!readOnly"
        type="primary"
        style="float:left;margin:0 10px 10px 0"
        @click="getXls"
      >下载模板</el-button>
      <el-upload
        v-if="!readOnly"
        :action="this.$http.defaults.baseURL+'api/busHcdj/importDetails/'"
        :on-success="importXq"
        :headers="myHeaders"
        :show-file-list="false"
        style="float:left"
      >
        <el-button type="success">导入</el-button>
      </el-upload>
      <el-table
        ref="processTable"
        :data="xqList"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column key="sjdq" align="center" prop="sjdq" label="涉及地区" min-width="200" />
        <el-table-column key="djje" align="center" prop="djje" label="登记金额（万元）" min-width="200" />
        <el-table-column key="hts" align="center" prop="hts" label="合同数" min-width="150" />
        <el-table-column key="hcdjrs" align="center" prop="hcdjrs" label="核查登记人数" min-width="150" />
        <el-table-column
          v-if="!readOnly"
          key="cz"
        >
          <template slot="header">
            <el-button
              type="success"
              @click="add2"
            >新增</el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
            >修改</el-button>
            <el-popconfirm title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="handleDelete(scope.$index)">
              <el-button slot="reference" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-form-item style="margin:10px 0">
        <el-button v-if="!readOnly" type="warning" :loading="loading" @click="submitForm(0)">办理中</el-button>
        <el-button v-if="!readOnly" type="success" :loading="loading" @click="submitForm(1)">已完成</el-button>
      </el-form-item>
    </el-form>
    <el-form v-if="auditFlag" ref="auditForm" :model="auditForm" class="form-container" label-width="200px">
      <el-form-item label="是否通过" prop="auditState">
        <el-radio-group v-model="auditForm.auditState">
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="0">未通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="auditFlag&&!auditForm.auditState" label="未通过原因" prop="auditResult">
        <el-input v-model="auditForm.auditResult" style="width:810px" />
      </el-form-item>
      <el-form-item style="margin:10px 0">
        <el-button type="success" :loading="loading" @click="submitAudit">审核</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import supervise from './supervise.vue'

const defaultForm = {
  djkssj: '',
  jhjssj: '',
  htsjgs: '',
  cqzcsjje: 0,
  cqzcwdfje: 0,
  cqzcry: '',
  bary: '',
  hcdjje: 0,
  hcdjhts: 0,
  id: null
}
const defaultForm2 = {
  sjdq: '',
  djje: '',
  hts: '',
  hcdjrs: ''
}
const defaultFileForm = {
  fileid: 0,
  remark: ''
}
const defaultAuditForm = {
  auditResult: '',
  auditState: 1
}
export default {
  name: 'ArticleDetail',
  components: { supervise },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    showDuban: {
      type: Boolean,
      default: false
    },
    cfajbh: {
      type: String,
      default: ''
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      hist: {},
      auditFlag: false,
      auditForm: Object.assign({}, defaultAuditForm),
      fileList: [],
      xqindex: -1,
      xqList: [],
      fjlList: [],
      fjList: [],
      dialogVisible2: false,
      dialogTitle2: '新增',
      fileDialogVisible: false,
      fileDialogTitle: '新增',
      roleName: '',
      deptName: '',
      realName: '',
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      postForm2: Object.assign({}, defaultForm2),
      filePostForm: Object.assign({}, defaultFileForm),
      loading: false,
      deptOption: [],
      userOption: [],
      processUserOption: [],
      priorityOption: [],
      classCodeOption: [],
      flowTypeOption: [],
      rules: {
        // hcdjje: [{ validator: validateRequire }],
        // hcdjhts: [{ validator: validateRequire }]
      },
      rules2: {
        sjdq: [{ validator: validateRequire }],
        djje: [{ validator: validateRequire }],
        hts: [{ validator: validateRequire }],
        hcdjrs: [{ validator: validateRequire }]
      },
      processListLoading: false,
      processList: [{ time: '第一次', unit1: '处非办', unit2: '公安局', date: '2021-05-10', limit: '10天', item: '尽快办理', result: '已办结' }, { time: '第二次', unit1: '处非办', unit2: '公安局', date: '2021-05-20', limit: '10天', item: '尽快办理', result: '已办结' }],
      processNow: {},
      mystep: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs['postForm']) {
          this.$refs['postForm'].resetFields()
        }
        this.mystep = this.step
        console.log('时间戳变化')
        this.getData(this.cfajbh)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    console.log(JSON.parse(localStorage.getItem('user')))
    this.roleName = JSON.parse(localStorage.getItem('user')).roleName
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
  },
  methods: {
    showSupervise() {
      return true
      // return JSON.parse(localStorage.getItem('user')).unitName === '处非办' || JSON.parse(localStorage.getItem('user')).unitName === '公安' || JSON.parse(localStorage.getItem('user')).unitName === '督查室' || JSON.parse(localStorage.getItem('user')).unitName === '政法委'
    },
    // 提交审核
    submitAudit() {
      // if (this.auditForm.auditState === 0 && this.auditForm.auditResult === '') {
      //   this.$message({
      //     message: '审核不通过请说明原因',
      //     type: 'error'
      //   })
      // } else {
      const para = {
        id: this.postForm.id,
        auditResult: this.auditForm.auditResult,
        auditState: this.auditForm.auditState
      }
      this.loading = true
      this.$http
        .post('/api/busHcdj/audit', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$emit('dialogHide')
            this.auditForm = Object.assign({}, defaultAuditForm)
            this.loading = false
            this.$router.back()
          } else {
            console.log('操作失败:' + response.data.message)
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.loading = false
        })
      // }
    },
    sumXq() {
      this.postForm.hcdjje = 0
      this.postForm.hcdjhts = 0
      this.xqList.forEach(item => {
        this.postForm.hcdjje += item.djje
        this.postForm.hcdjhts += item.hts
      })
    },
    importXq(response, file, fileList) {
      if (response.success) {
        this.xqList = response.result
        this.sumXq()
      } else {
        this.$message({
          message: '导入失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    getXls() {
      window.open('/hcdj.xlsx')
    },
    handleExceed(files, fileList) {
      this.$message.warning(`一次最多只能上传一个文件`)
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '导入失败:' + err,
        type: 'error',
        duration: 10000
      })
    },
    handleUploadSucc(response, file, fileList) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '导入成功!'
        })
        this.getList()
      } else {
        this.$message({
          message: '导入失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(response, file, fileList) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '导入成功!'
        })
        this.getList()
      } else {
        this.$message({
          message: '导入失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    handleDelete(index) {
      this.xqList.splice(index, 1)
      this.sumXq()
    },
    qztypeText(val) {
      if (this.qztypeList.find(item => item.value === val)) {
        return this.qztypeList.find(item => item.value === val).label
      } else {
        return ''
      }
    },
    ztText(val) {
      if (this.ztList.find(item => item.value === val)) {
        return this.ztList.find(item => item.value === val).label
      } else {
        return ''
      }
    },
    lxText(val) {
      if (this.lxList.find(item => item.value === val)) {
        return this.lxList.find(item => item.value === val).label
      } else {
        return ''
      }
    },
    xqText(row) {
      switch (row.lx) {
        case '0201':
          return '占比：' + row.zb + '%'
        case '0202':
          return '品牌：' + row.pp + '，车牌号：' + row.cph
        case '0203':
        case '0204':
          return '地址：' + row.dz + '，面积：' + row.mj + '平米'
        default:
          return row.xq
      }
    },
    submitForm2() {
      this.$refs.postForm2.validate(valid => {
        if (valid) {
          const item = { 'sjdq': this.postForm2.sjdq, 'djje': this.postForm2.djje, 'hts': this.postForm2.hts, 'hcdjrs': this.postForm2.hcdjrs }
          if (this.xqindex === -1) {
            this.xqList.push(item)
            this.sumXq()
          } else {
            console.log(item)
            console.log(this.xqindex)
            this.xqList[this.xqindex] = item
            this.sumXq()
          }
          this.dialogVisible2 = false
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm(flag) {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const para = {
            cfajbh: this.cfajbh,
            djkssj: this.postForm.djkssj,
            jhjssj: this.postForm.jhjssj,
            htsjgs: this.postForm.htsjgs,
            cqzcsjje: this.postForm.cqzcsjje,
            cqzcwdfje: this.postForm.cqzcwdfje,
            cqzcry: this.postForm.cqzcry,
            bary: this.postForm.bary,
            hcdjje: this.postForm.hcdjje,
            hcdjhts: this.postForm.hcdjhts,
            hcdjxqList: this.xqList,
            shzt: flag
          }
          this.loading = true
          this.$http
            .post('/api/busHcdj/saveHcdj', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm = Object.assign({}, defaultForm)
                this.loading = false
                this.$router.back()
              } else {
                console.log('操作失败:' + response.data.message)
                this.$message({
                  message: '操作失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleEdit(index, item) {
      this.postForm2 = item
      this.xqindex = index
      this.dialogVisible2 = true
      this.dialogTitle2 = '修改'
    },
    add2() {
      this.xqindex = -1
      this.postForm2 = Object.assign({}, defaultForm2)
      this.dialogVisible2 = true
      this.dialogTitle2 = '新增'
    },
    getHist() {
      const para = {
        actName: '核查登记',
        actState: 1,
        cfajbh: this.postForm.cfajbh,
        pageNum: 1,
        pageSize: 1
        // publishTime: this.listQuery.publishTime,
        // title: this.listQuery.title
      }
      this.$http
        .post('/api/busHist/queryByPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.hist = response.data.result.records[0]
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getData(cfajbh) {
      this.infoLoading = true
      if (cfajbh) {
        this.$http
          .get('/api/busHcdj/getHcdjById?&cfajbh=' + cfajbh)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              if (response.data.result.id) {
                console.log(response.data.result)
                this.postForm = response.data.result
                this.xqList = response.data.result.hcdjxqList

                const userinfo = JSON.parse(localStorage.getItem('user'))
                const unitName = userinfo.unitName
                const roleName = userinfo.roleName
                if (response.data.result.shzt === 1 && unitName === '公安' && roleName === '审核') {
                  this.auditFlag = true
                } else {
                  this.auditFlag = false
                }
                if (response.data.result.shzt === 3) {
                  this.getHist()
                }
              } else {
                this.postForm = Object.assign({}, defaultForm)
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
          this.xqList = []
          this.fjList = []
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
